<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Db;
use think\Model;
class Procedure extends Model
{

    // 表名
    protected $name = 'kuyou_bom_procedure';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->order(['id'=>'DESC'])->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order(['id'=>'DESC'])->select())->toArray();
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->find();
        if($detail){
            $detail['workshop_name'] = Db::name('kuyou_workshop')->where(['id'=>$detail['workshop_id']])->value('name');
            $purchase_info = Db::name('kuyou_bom_info')->where(['procedure_id'=>$detail['id']])->select();
            $unit = Db::name('kuyou_unit')->column('name','id');
            foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                $purchase_info[$purchase_info_k]['goods_image'] = (new Goods())->where(['goods_code'=>$purchase_info_v['goods_code']])->value('goods_image');
                $purchase_info[$purchase_info_k]['unit'] = (new Goods())->getGoodsUnit($purchase_info_v['goods_id']);
                $purchase_info[$purchase_info_k]['unit_name'] = isset($unit[$purchase_info_v['unit_id']])?$unit[$purchase_info_v['unit_id']]:'';
                $purchase_info[$purchase_info_k]['default_unit_name'] = isset($unit[$purchase_info_v['default_unit']])?$unit[$purchase_info_v['default_unit']]:'';
            }
            $detail['info_list'] = $purchase_info;
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关信息'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'bom_id|BOM清单ID'=>'require',
                'purchase_code|工序编号' =>'require',
                'name|名称'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],30);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Procedure())->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $bom = Db::name('kuyou_bom')->where(['id'=>$detail['bom_id']])->find();
                if(empty($bom)){
                    return ['status'=>500,'msg'=>'BOM清单不存在'];
                }
                $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                $number = 0;$all_money = 0;$data=[];
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'bom_id'        =>  $detail['bom_id'],
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'purchase'      =>  (float)$v['purchase'],
                            'number'        =>  (float)$v['number'],
                            'money'         =>  (float)$v['money'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                $detail['workshop_id'] = isset($detail['workshop_id'])?((float)$detail['workshop_id']):0;
                $detail['createtime'] = time();
                $detail['updatetime'] = time();
                $res = false;
                Db::startTrans();
                try {
                    if(!empty($detail)){
                        unset($detail['info_list']);
                        $res = (new Procedure())->insertGetId($detail);
                    }
                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['procedure_id'] = $res;
                    }
                    Db::name('kuyou_bom_info')->insertAll($data);
                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$detail['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        Db::name('kuyou_bom')->where(['id'=>$detail['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }

                if($res){
                    return ['status'=>200,'msg'=>$res];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'添加失败')];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'bom_id|BOM清单ID'=>'require',
                'purchase_code|工序编号' =>'require',
                'name|名称'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],30);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Procedure())->where(['purchase_code'=>$detail['purchase_code'],'id'=>['<>',$detail['id']]])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $id = $detail['id'];unset($detail['id']);
                $bom = Db::name('kuyou_bom')->where(['id'=>$detail['bom_id']])->find();
                if(empty($bom)){
                    return ['status'=>500,'msg'=>'BOM清单不存在'];
                }
                $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                $number = 0;$all_money = 0;$data=[];
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'bom_id'        =>  $detail['bom_id'],
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'purchase'      =>  (float)$v['purchase'],
                            'number'        =>  (float)$v['number'],
                            'money'         =>  (float)$v['money'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                $detail['workshop_id'] = isset($detail['workshop_id'])?((float)$detail['workshop_id']):0;
                $detail['updatetime'] = time();

                $res = false;
                Db::startTrans();
                try {
                    unset($detail['info_list']);
                    $res = (new Procedure())->where(['id'=>$id])->update($detail);

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['procedure_id'] = $id;
                    }
                    Db::name('kuyou_bom_info')->where(['procedure_id'=>$id])->delete();
                    Db::name('kuyou_bom_info')->insertAll($data);
                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$detail['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        Db::name('kuyou_bom')->where(['id'=>$detail['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }

                if($res){
                    return ['status'=>200,'msg'=>'更新成功'];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'更新失败')];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $list = (new Procedure())->where(['id'=>['in',$id]])->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::name('kuyou_bom_info')->where(['procedure_id'=>$v['id']])->delete();
                    $count = Db::name('kuyou_bom_info')->where(['bom_id'=>$v['bom_id']])->field('sum(number) as number,sum(money) as money')->select();
                    Db::name('kuyou_bom')->where(['id'=>$v['bom_id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $count = 0;
            }

            if($count){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }
}
